package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.louwowo.cache.service.IWendaStatisRedisService;
import cn.wolfcode.louwowo.cache.vo.HuidaStatisVO;
import cn.wolfcode.louwowo.cache.vo.UserWendaStatisVO;
import cn.wolfcode.luowowo.article.domain.Huida;
import cn.wolfcode.luowowo.article.domain.Wenda;
import cn.wolfcode.luowowo.article.query.HuidaQuery;
import cn.wolfcode.luowowo.article.query.WendaQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IHuidaService;
import cn.wolfcode.luowowo.article.service.IWendaService;
import cn.wolfcode.luowowo.article.service.IWendaTagService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.service.ISearchService;
import cn.wolfcode.luowowo.search.template.TravelTemplate;
import cn.wolfcode.luowowo.search.template.WenDaTemplate;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("wenda")
public class WendaController {
    @Reference
    private IWendaService wendaService;
    @Reference
    private IHuidaService huidaService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IWendaTagService wendaTagService;
    @Reference
    private ISearchService searchService;
    @Reference
    private IWendaStatisRedisService wendaStatisRedisService;

    @RequestMapping("")
    public String wenda(Model model, @ModelAttribute("qo")WendaQuery qo){
        PageInfo pageInfo = wendaService.query(qo);
        List<Wenda> wendas = pageInfo.getList();
        for (Wenda wenda : wendas) {
            Long wendaId = wenda.getId();
            List<Huida> huidas = huidaService.selectByWendaId(wendaId);
            if (huidas.size() > 0){
                Huida huida = huidas.get(0);
                huida.setThumbsupnum(wendaStatisRedisService.getHuidaStatisVO(huida.getId()).getThumbsupnum());
                wenda.setHotHuida(huida);
            }
        }
        model.addAttribute("pageInfo", pageInfo);
        return "wenda/wenda";
    }

    //添加问答页面
    @RequireLogin
    @RequestMapping("input")
    public String input(Model model){
        model.addAttribute("dests", destinationService.getDestByDeep(3));
        model.addAttribute("tags", wendaTagService.selectAll());
        return "wenda/input";
    }

    //发布问题
    @RequestMapping("save")
    @ResponseBody
    public Object save(Wenda wenda, @UserParam UserInfo userInfo){
        if (userInfo == null){
            return AjaxResult.UNLOGIN();
        }
        wenda.setAuthor(userInfo);
        wendaService.saveOrUpdate(wenda);
        return new AjaxResult();
    }

    //问答详细页面
    @RequestMapping("detail")
    public String wendaD(Model model, Long id, @ModelAttribute("qo")HuidaQuery qo, @UserParam UserInfo userInfo){
        Wenda wenda = wendaService.get(id);
        model.addAttribute("wenda", wenda);
        //相关问题,不查询自己
        List<Wenda> likeWenda = wendaService.selectByDestIdT5(wenda.getDest().getId(), wenda.getId());
        model.addAttribute("likeWenda", likeWenda);
        //回答分页
        qo.setWendaId(wenda.getId());
        PageInfo pageInfo = huidaService.query(qo);
        List<Huida> huidas = pageInfo.getList();
        //查询顶数
        for (Huida huida : huidas) {
            HuidaStatisVO statisVO = wendaStatisRedisService.getHuidaStatisVO(huida.getId());
            if (statisVO != null){
                huida.setThumbsupnum(statisVO.getThumbsupnum());
            }
        }
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("userInfo", userInfo);
        //页面被访问,浏览数增加
        wenda.setAddViewnum(1);
        wendaService.updateNum(wenda);
        return "wenda/wendaDetail";
    }

    //回答
    @RequestMapping("huida")
    @ResponseBody
    public Object huida(Huida huida, Model model, @UserParam UserInfo userInfo){
        if (userInfo == null){
            return AjaxResult.UNLOGIN();
        }
        huida.setAuthor(userInfo);
        huidaService.saveOrUpdate(huida);
        //用户回答后用户回答数增加,排行积分增加
        wendaStatisRedisService.addHuida(userInfo.getId(), 1);
        //把问答的ID返回,页面跳转
        AjaxResult result = new AjaxResult();
        result.setData(huida.getWenda().getId());
        return result;
    }

    //顶操作
    @RequestMapping("ding")
    @ResponseBody
    public Object ding(Long hId, @UserParam UserInfo userInfo){
        if (userInfo == null){
            return AjaxResult.UNLOGIN();
        }
        //一个回答一个用户一天只能顶一次
        boolean ref = wendaStatisRedisService.ding(hId, userInfo.getId(), 1);
        //顶成功后,被顶回答的作者被顶数增加,被顶排行积分增加
        if (ref){
            Huida huida = huidaService.get(hId);
            Long authorId = huida.getAuthor().getId();
            wendaStatisRedisService.addDing(authorId, 1);
        }
        //返回顶的数量给页面
        AjaxResult result = new AjaxResult(ref, "");
        result.setData(wendaStatisRedisService.getHuidaStatisVO(hId).getThumbsupnum());
        return result;
    }

    //问答排名
    @RequestMapping("top")
    public String top(Integer type, Integer rank, Model model){
        List<UserWendaStatisVO> vos = wendaStatisRedisService.getTop(type, rank);
        model.addAttribute("vos", vos);
        return "wenda/paimingTpl";
    }


    /**
     * 查询问答
     * @param model
     * @param qo
     * @param userInfo
     * @param id
     * @return
     */
    @RequestMapping("search")
    public String search(Model model,@ModelAttribute("qo") SearchQueryObject qo,@UserParam UserInfo userInfo,Long id){
        Page<WenDaTemplate> page = searchService.searchWithHighlight(WenDaTemplate.INDEX_NAME,
                WenDaTemplate.TYPE_NAME, WenDaTemplate.class, qo, "title");
        model.addAttribute("page",page);
        return "wenda/search";
    }










    @Value("${file.path}")
    private String filePath;
    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);
        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }
}
